<template>
  <div class="addEditArticlePageCont">
    <div class="title">当前位置：文章管理 / {{ title }}</div>
    <div class="addEditArticlePageMian">
      <Form ref="form" :model="editorInfo" :rules="rules" :label-width="110">
        <FormItem label="文章标题：" prop="articleTitle" required>
          <!-- <Select v-model="editorInfo.articleTags" placeholder="请选择文章标签" filterable
            style="width: 100%">
            <Option v-for="(item, index) in articleTagsList" :value="String(item.labelId)"
              :disabled="item.holdFlag == 1" :key="index">{{
                item.holdFlag == 1
                  ? item.ztLabelType + "(已维护)"
                  : item.ztLabelType
              }}</Option>
          </Select> -->
          <Input v-model="editorInfo.articleTitle" placeholder="请输入文章标题" maxlength="15"
            show-word-limit></Input>
        </FormItem>
        <FormItem label="原始数据："  v-if="editorInfo.articleContent">
          <div class="yuanText">原始数据仅用于查看，如需编辑请通过下方“正文”与“图片/视频”进行修改</div>
          <div class="articleContentBox" v-html="editorInfo.articleContent"></div>
        </FormItem>
        <FormItem label="文章正文：" prop='newArticleContent' required>
           <Input v-model="editorInfo.newArticleContent" maxlength="200"
            :autosize="{minRows: 6,maxRows: 6}" show-word-limit type="textarea"
            placeholder="请输入文章正文..." />
        </FormItem>
        <FormItem v-if='sensitiveWords' label="敏感词汇：">
          <div class="wrong">
            {{sensitiveWords}}
          </div>
        </FormItem>
        <FormItem label="图片/视频：" class="FormItemUpload">
          <div v-if="articleImgFlag&&editorInfo.fileUrl" class="demo-upload-list">
            <img :src="editorInfo.fileUrl" />
            <div class="demo-upload-list-cover">
              <Icon type="ios-eye-outline" @click="handleView(editorInfo.fileUrl,'img')"></Icon>
              <Icon type="ios-trash-outline" @click="handleRemove(editorInfo.fileUrl,'img')"></Icon>
            </div>
          </div>
          <div v-if="articleImgFlag&&editorInfo.videoUrl" class="demo-upload-list">
            <video controls="controls" :src="editorInfo.videoUrl" >
              您的浏览器不支持 video 标签
            </video>
            <div class="demo-upload-list-cover">
              <Icon type="ios-eye-outline" @click="handleView(editorInfo.fileUrl,'video')"></Icon>
              <Icon type="ios-trash-outline" @click="handleRemove(editorInfo.fileUrl,'video')"></Icon>
            </div>
          </div>
          <Upload ref="upload" v-if="!articleImgFlag || !editorInfo.fileUrl && !editorInfo.videoUrl"
            :show-upload-list="false" :data="upload.data" name="multipartFile"
            :headers="upload.headers" :on-success="handleSuccess" :format="['jpg','jpeg','gif','bmp','png','mp4','avi','wmv','rmvb']"
            type="drag" 
             :max-size="30720" :on-exceeded-size="handleMaxSize"
            :on-format-error="handleFormatError" :action="upload.reqUrl"
            :before-upload = 'beforeUpload'
            style="display: inline-block; width: 58px">
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <!-- <Upload ref="upload" v-if="editorInfo.fileList.length > 0 ? false : true"
            :show-upload-list="false" :data="upload.data" name="multipartFile"
            :headers="upload.headers" :on-success="handleSuccess" :format="['jpg', 'png']"
            :max-size="2048" type="drag" :on-exceeded-size="handleMaxSize"
            :on-format-error="handleFormatError" :action="upload.reqUrl"
            style="display: inline-block; width: 58px">
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <span class="imageSize" v-if="editorInfo.fileList.length > 0 ? false : true">建议尺寸
            750*422 大小在1M内</span> -->
        </FormItem>
        <div class="tips">
          Tips：<br/>
          （1）仅能上传1张图片或1个视频，内容大小不超过30M；<br/>
          （2）内容建议高度341像素，宽度不限；
        </div>
        <div class="footer">
          <Button type="primary" :loading="loading"
            @click="addEditArticleSubmit">{{ $route.query.type == "add" ? "提交审核" : "确定" }}</Button>
          <Button @click="previewClick" style="margin-left: 8px">预览</Button>
          <Button @click="addEditArticleReset" style="margin-left: 8px">取消</Button>
        </div>
      </Form>
    </div>
    <!-- 图片放大 -->
    <preview-image :images="preViewImg" :showIndex="0" ref="preViewImage">
    </preview-image>

    <preview-video :videoUrl="editorInfo.videoUrl"  ref="preViewVideo">
    </preview-video>

    <preview :editorInfo="editorInfo"  ref="preView">
    </preview>

  </div>
</template>
<script>
  import toolMgr from '@/biz/base/tool.js'
  // import secret from '@/common/secret.js'
  // import dtEditor from '@/components/dt/editor/index.vue'
  import articleMgr from '@/biz/article/article'
  import infoMgr from '@/biz/base/info'

  import previewVideo from "@/components/previewVideo.vue"
  import preview from "./components/preview.vue"

  export default {
    components: {    
      previewVideo,
      preview
    },
    data() {
      return {
        preViewImg: [],
        upload: toolMgr.unloadImage({ title: new Date().getTime(), }),
        title: '',
        articleTagsList: [],
        editorInfo: {
          articleTitle: '',
          fileUrl: '',
          videoUrl: '',
          articleContent: null,
          newArticleContent:null
        },
        rules: {
          articleTitle: [
            { required: true, message: '请输入文章标题', trigger: 'change' },
          ],
          newArticleContent: [
            { required: true, message: '请输入正文', trigger: 'change' },
          ],
        },
        loading: false,
        buildingId: '',
        articleId: null,
        sensitiveWords: null,
        articleImgFlag:true
      }
    },
    methods: {
      // 文章管理
      addEditArticleSubmit() {
        console.log('提交');
        this.$refs.form.validate((valid) => {
          console.log(valid,'111');
          if (valid) {
            let params = {
              buildingId: this.buildingId,
              // labelIdList: Number(this.editorInfo.articleTags),
              articleTitle: this.editorInfo.articleTitle,
              newArticleContent: this.editorInfo.newArticleContent,
              articleImage: this.editorInfo.fileUrl?this.editorInfo.fileUrl:this.editorInfo.videoUrl?this.editorInfo.videoUrl:'',
              cityId: this.$dt.buildInfo().cityId,
              city: this.$dt.buildInfo().city,
            }
            this.loading = true
            if (this.articleId) {
              params.articleId = this.articleId
            }
            infoMgr.create(params).then(res => {

              console.log(res,'文章新增成功');
              this.loading = false
              this.sensitiveWords = res.sensitiveWords && res.sensitiveWords.length >
                0 ? res.sensitiveWords : null
              this.articleId = res.articleId
              if (!this.sensitiveWords) {
                this.$Message.success(this.$route.query.type == 'add' ? '新增文章成功!' :
                  '修改文章成功!')
                this.$router.go(-1)
              }
            }).catch((err) => {
              this.$Message.error(err)
              this.loading = false
            })
          }else{
            console.log('222');
          }
        })
      },
      // form 表单
      addEditArticleReset() {
        this.$router.go(-1)
      },
      previewClick(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$refs.preView.show()
          }
        })
        
      },
      // 上传前
      beforeUpload(){
        this.editorInfo.videoUrl = ''
        this.editorInfo.fileUrl = ""
      },
      // 上传成功回调
      handleSuccess(res, file) {
        
        console.log(res,'上传成功');
        if (res.code == '200') {
           this.editorInfo.videoUrl = ''
            this.editorInfo.fileUrl = ""
            this.articleImgFlag = res.data.imageURL?true:false
          let suffix = res.data.imageURL.split('.').pop().toLowerCase()
          if(['mp4','avi','wmv','rmvb'].indexOf(suffix)>-1){
            console.log('我是视频');
            this.editorInfo.videoUrl=res.data.imageURL
          }else{
            this.editorInfo.fileUrl=res.data.imageURL
          }
          
        } else {
          console.log('上传出错')
        }
      },
      handleMaxSize(file) {
        this.$Message.warning('单个图片不能超过30 M')
      },
      // 文件格式验证失败
      handleFormatError(file) {
        this.$Message.warning('请上传图片或视频。')
      },
      handleView(val,type) {
        if(type=='img'){
          this.preViewImg = [val]
          this.$refs.preViewImage.show()
        }else{
          this.$refs.preViewVideo.show()
        }
        
      },
      handleRemove(val,type) {
        if(type=='img'){
          this.editorInfo.fileUrl=''
        }else{
           this.editorInfo.videoUrl=''
        }
  
      },
      //获取文章标签列表
      // getNotes() {
      //   let params = {
      //     projectSummaryFlag: 2,
      //     buildingId: this.$dt.buildInfo().housesId,
      //   }
      //   articleMgr.articleLabel(params).then((res) => {
      //     this.articleTagsList = res.list
      //   })
      // },
    },
    created() {
      //获取文章标签
      // this.getNotes()
      // 判断新增与编辑
      this.articleId = this.$route.query.articleId
      if (this.$route.query.type == 'add') {
        this.title = '新增文章'
        document.title = '新增文章'
      } else if (this.$route.query.type == 'edit') {
        this.title = '编辑文章'
        document.title = '编辑文章'
        articleMgr.articleGet({ articleId: this.$route.query.articleId }).then((res) => {
          if (res) {
            console.log(res,'文章详情');
            this.editorInfo.articleTitle = res.articleTitle
            this.editorInfo.fileUrl = res.articleImage ? [{ url: res.articleImage }] : ''
            this.editorInfo.articleContent = res.articleContent
            this.editorInfo.newArticleContent = res.newArticleContent
            this.sensitiveWords = res.sensitiveWords && res.sensitiveWords.length > 0 ? res
              .sensitiveWords : null

            

          this.articleImgFlag = res.articleImage?true:false
          if(res.articleImage){

            let suffix =res.articleImage.split('.').pop().toLowerCase()
            if(['mp4','avi','wmv','rmvb'].indexOf(suffix)>-1){
              console.log('我是视频');
              this.editorInfo.videoUrl=res.articleImage
              this.editorInfo.fileUrl=''
            }else{
              this.editorInfo.fileUrl=res.articleImage
              this.editorInfo.videoUrl=''
            }

                
            }
          }

        }).catch((err) => {
          this.$Message.error(err)
        })
      }
    },
    mounted() {
      this.buildingId = JSON.parse(this.$tool.getStorage('caseBuildingId'))
    },
  }
</script>
<style lang="scss" scoped>
  .addEditArticlePageCont {
    .title {
      background-color: #f5f5f5;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
      padding: 0 14px 10px;
    }

    .addEditArticlePageMian {
      margin-top: 16px;
      width: 800px;
    }
  }

  .footer {
    text-align: center;

    button {
      margin: 0 10px;
    }
  }

  // 上传
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }
   .demo-upload-list video {
    width: 100%;
    height: 100%;
  }


  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .FormItemUpload .ivu-form-item-content {
    display: flex;
  }

  .imageSize {
    display: inline-block;
    margin-left: 16px;
    vertical-align: top;
    padding-top: 16px;
  }

  .wrong {
    color: red;
  }
  .tips{
    font-size:14px;
    color:#999;
    line-height: 1.8;
    padding-left:109px;
    padding-bottom: 50px;
  }
  .articleContentBox{
    border:1px solid #ccc;
    padding:20px;
    max-height: 400px;
    overflow-y:auto;
    max-width:100%;
    *{
      max-width: 100%;
    }
  }
  .yuanText{
    font-size:12px;
    color:rgb(247, 63, 63)
  }
</style>